<?php
// 开启所有错误报告
error_reporting(E_ALL);
ini_set('display_errors', 1);

// 启动会话并验证登录状态
session_start();

// 验证教师登录
if (!isset($_SESSION['isLoggedIn']) || !$_SESSION['isLoggedIn'] || $_SESSION['role'] !== 'teacher') {
    header('Location: login.php');
    exit;
}

// 从会话中获取教师ID
$teacherID = isset($_SESSION['userId']) ? intval($_SESSION['userId']) : null;
if ($teacherID === null) {
    header('Location: login.php');
    exit;
}
?>

<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <title>教师管理系统</title>
</head>

<body class="bg-gray-100 font-sans">
    <div class="container mx-auto p-8">
        <!-- 添加欢迎信息和注销按钮 -->
        <div class="flex justify-between items-center mb-6">
            <h1 class="text-2xl font-bold text-gray-800">欢迎, <?php echo htmlspecialchars($_SESSION['username'] ?? '教师'); ?></h1>
            <a href="logout.php" class="bg-red-500 hover:bg-red-600 text-white font-bold py-2 px-4 rounded">注销</a>
        </div>
       
        <nav class="flex space-x-4 mb-8">
            <a href="?page=info" class="bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded">教师信息</a>
            <a href="?page=courses" class="bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded">所教课程</a>
            <a href="?page=grades" class="bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded">学生成绩</a>
        </nav>
        
        <div class="bg-white p-8 rounded shadow-md">
            <?php
            // 数据库连接配置
            $servername = "localhost";
            $username = "root";
            $password = "874604";
            $dbname = "root";

            // 创建连接
            $conn = new mysqli($servername, $username, $password, $dbname);

            // 检查连接
            if ($conn->connect_error) {
                die("连接失败: " . $conn->connect_error);
            }

            // 1. 管理自己的信息
            function manageTeacherInfo($conn, $teacherID) {
                if (isset($_POST['update'])) {
                    $name = $_POST['name'];
                    $gender = $_POST['gender'];
                    $departmentID = $_POST['department'];
                    $title = $_POST['title'];

                    // 使用预处理语句防止SQL注入
                    $stmt = $conn->prepare("UPDATE Teacher SET Name = ?, Gender = ?, DepartmentID = ?, Title = ? WHERE TeacherID = ?");
                    $stmt->bind_param("ssisi", $name, $gender, $departmentID, $title, $teacherID);
                    
                    if ($stmt->execute()) {
                        echo '<p class="text-green-500 mb-4">信息更新成功</p>';
                        // 更新会话中的用户名
                        $_SESSION['username'] = $name;
                    } else {
                        echo '<p class="text-red-500 mb-4">信息更新失败: ' . $conn->error . '</p>';
                    }
                    $stmt->close();
                }

                $stmt = $conn->prepare("SELECT t.*, d.DepartmentName FROM Teacher t JOIN Department d ON t.DepartmentID = d.DepartmentID WHERE t.TeacherID = ?");
                $stmt->bind_param("i", $teacherID);
                $stmt->execute();
                $result = $stmt->get_result();

                if ($result->num_rows > 0) {
                    $row = $result->fetch_assoc();
                    echo '<h2 class="text-2xl font-bold text-gray-800 mb-4">教师信息</h2>';
                    echo '<p class="mb-2">姓名: ' . htmlspecialchars($row['Name']) . '</p>';
                    $gender = $row['Gender'] === 'male' ? '男' : ($row['Gender'] === 'female' ? '女' : '未知');
                    echo '<p class="mb-2">性别: ' . $gender . '</p>';
                    echo '<p class="mb-2">所属院系: ' . htmlspecialchars($row['DepartmentName']) . '</p>';
                    echo '<p class="mb-4">职称: ' . htmlspecialchars($row['Title']) . '</p>';

                    echo '<a href="?page=info&edit=1" class="text-blue-500 hover:underline">修改信息</a>';

                    if (isset($_GET['edit']) && $_GET['edit'] == 1) {
                        echo '<h2 class="text-2xl font-bold text-gray-800 mt-8 mb-4">修改教师信息</h2>';
                        echo '<form method="post">';
                        echo '<div class="mb-4">';
                        echo '<label for="name" class="block text-gray-700 font-bold mb-2">姓名:</label>';
                        echo '<input type="text" id="name" name="name" value="' . htmlspecialchars($row['Name']) . '" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" required>';
                        echo '</div>';
                        
                        echo '<div class="mb-4">';
                        echo '<label for="gender" class="block text-gray-700 font-bold mb-2">性别:</label>';
                        echo '<select id="gender" name="gender" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" required>';
                        echo '<option value="male" ' . ($row['Gender'] === 'male' ? 'selected' : '') . '>男</option>';
                        echo '<option value="female" ' . ($row['Gender'] === 'female' ? 'selected' : '') . '>女</option>';
                        echo '</select>';
                        echo '</div>';

                        $deptSql = "SELECT * FROM Department";
                        $deptResult = $conn->query($deptSql);
                        echo '<div class="mb-4">';
                        echo '<label for="department" class="block text-gray-700 font-bold mb-2">所属院系:</label>';
                        echo '<select id="department" name="department" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" required>';
                        while ($deptRow = $deptResult->fetch_assoc()) {
                            echo '<option value="' . $deptRow['DepartmentID'] . '" ' . ($deptRow['DepartmentID'] == $row['DepartmentID'] ? 'selected' : '') . '>' . htmlspecialchars($deptRow['DepartmentName']) . '</option>';
                        }
                        echo '</select>';
                        echo '</div>';

                        echo '<div class="mb-4">';
                        echo '<label for="title" class="block text-gray-700 font-bold mb-2">职称:</label>';
                        echo '<input type="text" id="title" name="title" value="' . htmlspecialchars($row['Title']) . '" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" required>';
                        echo '</div>';
                        echo '<input type="submit" name="update" value="更新信息" class="bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded">';
                        echo '</form>';
                    }
                } else {
                    echo '<p class="text-gray-500 mb-4">未找到教师信息</p>';
                }
                $stmt->close();
            }

            // 2. 管理自己所教课程
            function manageTaughtCourses($conn, $teacherID) {
                $stmt = $conn->prepare("SELECT 
                    c.CourseName, 
                    co.Year, 
                    co.Semester, 
                    COUNT(e.EnrollmentID) AS enrollment_count, 
                    d.DepartmentName 
                FROM 
                    Course c
                JOIN 
                    CourseOffering co ON c.CourseID = co.CourseID
                LEFT JOIN 
                    Enrollment e ON co.OfferingID = e.OfferingID
                LEFT JOIN 
                    Department d ON c.DepartmentID = d.DepartmentID
                WHERE 
                    co.TeacherID = ?
                GROUP BY 
                    c.CourseName, co.Year, co.Semester, d.DepartmentName");
                
                $stmt->bind_param("i", $teacherID);
                $stmt->execute();
                $result = $stmt->get_result();

                if ($result->num_rows > 0) {
                    echo '<h2 class="text-2xl font-bold text-gray-800 mb-4">所教课程信息</h2>';
                    echo '<table class="min-w-full divide-y divide-gray-200">';
                    echo '<thead class="bg-gray-50">';
                    echo '<tr>';
                    echo '<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">课程名称</th>';
                    echo '<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">开课年份</th>';
                    echo '<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">学期</th>';
                    echo '<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">选课人数</th>';
                    echo '<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">所属院系名称</th>';
                    echo '</tr>';
                    echo '</thead>';
                    echo '<tbody class="bg-white divide-y divide-gray-200">';

                    while ($row = $result->fetch_assoc()) {
                        $semester = $row['Semester'] === 'spring' ? '春季' : '秋季';
                        echo '<tr>';
                        echo '<td class="px-6 py-4 whitespace-nowrap">' . htmlspecialchars($row['CourseName']) . '</td>';
                        echo '<td class="px-6 py-4 whitespace-nowrap">' . htmlspecialchars($row['Year']) . '</td>';
                        echo '<td class="px-6 py-4 whitespace-nowrap">' . $semester . '</td>';
                        echo '<td class="px-6 py-4 whitespace-nowrap">' . htmlspecialchars($row['enrollment_count']) . '</td>';
                        echo '<td class="px-6 py-4 whitespace-nowrap">' . ($row['DepartmentName'] ? htmlspecialchars($row['DepartmentName']) : '公共课') . '</td>';
                        echo '</tr>';
                    }

                    echo '</tbody>';
                    echo '</table>';
                } else {
                    echo '<p class="text-gray-500 mb-4">未找到所教课程信息</p>';
                }
                $stmt->close();
            }

            // 3. 管理成绩
            function manageGrades($conn, $teacherID) {
                if (isset($_POST['update_grades'])) {
                    $offeringID = intval($_POST['offering_id']);
                    $stmt = $conn->prepare("UPDATE Enrollment SET Grade = ? WHERE EnrollmentID = ? AND EXISTS (
                        SELECT 1 FROM CourseOffering WHERE OfferingID = ? AND TeacherID = ?
                    )");
                    
                    foreach ($_POST['grades'] as $enrollmentID => $grade) {
                        if (is_numeric($grade) && $grade >= 0 && $grade <= 100) {
                            $enrollmentID = intval($enrollmentID);
                            $grade = intval($grade);
                            $stmt->bind_param("iiii", $grade, $enrollmentID, $offeringID, $teacherID);
                            $stmt->execute();
                        }
                    }
                    $stmt->close();
                    echo '<p class="text-green-500 mb-4">成绩更新成功</p>';
                }

                $stmt = $conn->prepare("SELECT 
                    c.CourseName, 
                    co.OfferingID, 
                    co.Year, 
                    co.Semester 
                FROM 
                    Course c
                JOIN 
                    CourseOffering co ON c.CourseID = co.CourseID
                WHERE 
                    co.TeacherID = ?");
                $stmt->bind_param("i", $teacherID);
                $stmt->execute();
                $result = $stmt->get_result();

                if ($result->num_rows > 0) {
                    echo '<h2 class="text-2xl font-bold text-gray-800 mb-4">学生成绩信息</h2>';
                    while ($courseRow = $result->fetch_assoc()) {
                        $semester = $courseRow['Semester'] === 'spring' ? '春季' : '秋季';
                        echo '<h3 class="text-xl font-bold text-gray-800 mb-2">' . htmlspecialchars($courseRow['CourseName']) . ' (' . htmlspecialchars($courseRow['Year']) . '年 ' . $semester . ')</h3>';
                        echo '<a href="?page=grades&offering_id=' . $courseRow['OfferingID'] . '" class="text-blue-500 hover:underline">修改成绩</a>';

                        if (isset($_GET['offering_id']) && $_GET['offering_id'] == $courseRow['OfferingID']) {
                            $enrollmentSql = "SELECT 
                                e.EnrollmentID, 
                                s.Name, 
                                e.Grade 
                            FROM 
                                Enrollment e
                            JOIN 
                                Student s ON e.StudentID = s.StudentID
                            WHERE 
                                e.OfferingID = ?";
                            $enrollmentStmt = $conn->prepare($enrollmentSql);
                            $enrollmentStmt->bind_param("i", $courseRow['OfferingID']);
                            $enrollmentStmt->execute();
                            $enrollmentResult = $enrollmentStmt->get_result();

                            if ($enrollmentResult->num_rows > 0) {
                                echo '<form method="post">';
                                echo '<input type="hidden" name="offering_id" value="' . $courseRow['OfferingID'] . '">';
                                echo '<table class="min-w-full divide-y divide-gray-200 mt-4">';
                                echo '<thead class="bg-gray-50">';
                                echo '<tr>';
                                echo '<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">学生姓名</th>';
                                echo '<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">当前成绩</th>';
                                echo '<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">修改成绩</th>';
                                echo '</tr>';
                                echo '</thead>';
                                echo '<tbody class="bg-white divide-y divide-gray-200">';

                                while ($enrollmentRow = $enrollmentResult->fetch_assoc()) {
                                    echo '<tr>';
                                    echo '<td class="px-6 py-4 whitespace-nowrap">' . htmlspecialchars($enrollmentRow['Name']) . '</td>';
                                    echo '<td class="px-6 py-4 whitespace-nowrap">' . ($enrollmentRow['Grade'] ? htmlspecialchars($enrollmentRow['Grade']) : '未录入') . '</td>';
                                    echo '<td class="px-6 py-4 whitespace-nowrap">';
                                    echo '<input type="number" name="grades[' . $enrollmentRow['EnrollmentID'] . ']" min="0" max="100" value="' . ($enrollmentRow['Grade'] ? htmlspecialchars($enrollmentRow['Grade']) : '') . '" class="shadow appearance-none border rounded py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline">';
                                    echo '</td>';
                                    echo '</tr>';
                                }

                                echo '</tbody>';
                                echo '</table>';
                                echo '<input type="submit" name="update_grades" value="更新成绩" class="bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded mt-4">';
                                echo '</form>';
                            }
                            $enrollmentStmt->close();
                        }
                    }
                } else {
                    echo '<p class="text-gray-500 mb-4">未找到所教课程的学生成绩信息</p>';
                }
                $stmt->close();
            }

            $page = isset($_GET['page']) ? $_GET['page'] : 'info';

            switch ($page) {
                case 'info':
                    manageTeacherInfo($conn, $teacherID);
                    break;
                case 'courses':
                    manageTaughtCourses($conn, $teacherID);
                    break;
                case 'grades':
                    manageGrades($conn, $teacherID);
                    break;
            }

            // 关闭连接
            $conn->close();
            ?>
        </div>
    </div>
</body>
</html>